  <!-- 商品管理 -->
<template>
  <div class="main-body">
    <header class="main-body-search">
      <el-form :model="search" @submit.native.prevent>
        <el-row :gutter="50" type="flex" justify="space-between">
          <el-col :span="12">
            <el-button type="primary" @click="showEdit(false)" icon="el-icon-plus">新增商品</el-button>
            <el-button type="warning" @click="start" v-if="!drop" plain>排序</el-button>
            <el-button type="warning" @click="stop" v-else plain>保存排序</el-button>
          </el-col>
          <el-col :span="12" style="text-align: right;">
            <el-form-item label class="nja-form-line">
              <el-input
                style="width: 300px;"
                v-model.trim="search.keyword"
                placeholder="商品名称或编码"
                clearable
                @keyup.enter.native="searchHandle"
              >
                <div
                  slot="prefix"
                  style="height: 100%;width: 100%;display: flex;justify-content: center;align-items: center;"
                >
                  <i class="el-icon-search"></i>
                </div>
                <el-button type="primary" slot="append" @click="searchHandle">查询</el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </header>
    <el-main class="main-body-table draggable">
      <div class="table-shadow"></div>
      <el-table
        :data="tableData"
        :default-sort="{ prop: 'createTime', order: 'descending' }"
        stripe
        row-key="id"
        style="width: 100%"
        height="calc(100vh - 250px)"
        @sort-change="sortChange"
        ref="dataTableRef"
      >
        <el-table-column type="index" fixed="left" label="#" align="center"></el-table-column>
        <el-table-column
          v-bind="f"
          :sortable="f.sortable"
          show-overflow-tooltip
          :prop="f.name"
          :min-width="f.minW || '100px'"
          align="center"
          v-for="(f, i) in fileds"
          :key="i"
        >
          <template slot-scope="scope">
            <template v-if="f.fieldType === 'dataSource'">{{ dictData[f.data][scope.row[f.name]] }}</template>
            <template v-else-if="f.fieldType === 'dict'">{{ scope.row[f.name] }}</template>
            <template v-else-if="f.fieldType === 'img'">
              <el-image class="list-img" v-if="scope.row.imageUrl" :src="scope.row.imageUrl">
                <div slot="error" class="image-slot">暂无</div>
              </el-image>
              <el-image v-else class="list-img">
                <div slot="error" class="image-slot">暂无</div>
              </el-image>
            </template>
            <template v-else-if="f.fieldType === 'tag'">
              <el-tag
                class="mytag"
                v-for="(t, i) in scope.row[f.name].split(',')"
                size="mini"
                :key="i"
              >{{ t}}</el-tag>
            </template>
            <template v-else-if="f.fieldType === 'switch'">
              <el-switch
                v-model="scope.row[f.name]"
                size="mini"
                :active-value="1"
                :inactive-value="0"
                @change="changeStatus(scope.row, f.name)"
                active-color="#13ce66"
                inactive-color="#999"
              ></el-switch>
            </template>
            <template v-else>{{ scope.row[f.name] }}</template>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="160px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="default"
              v-if="scope.row.status == 1"
              @click="showEdit(scope.row)"
            >查看</el-button>
            <el-button size="mini" type="primary" v-else @click="showEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="warning" @click="deleteRow(scope.row)">删除</el-button>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无数据"></el-empty>
        </template>
      </el-table>
      <!--工具条-->
      <el-pagination
        class="main-body-table-page"
        @size-change="handleSizeChange"
        :page-sizes="[10, 20, 50, 100]"
        layout="sizes, total, prev, pager, next, jumper"
        @current-change="handleCurrentChange"
        :current-page="search.current"
        :page-size="search.size"
        :total="search.total"
      ></el-pagination>
    </el-main>
    <el-dialog
      :title="`${!form.id ? '新增商品' : (form.status == 1 ? '查看商品' : '编辑商品')}`"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      center
      v-dialogDrag
      custom-class="mydialog"
      width="900px"
    >
      <el-tabs type="card" v-model="currentTab" tab-position="top" @tab-click="loading = true">
        <el-tab-pane label="商品信息" name="base" v-loading="loading">
          <el-form
            ref="form"
            class="formlayout"
            :model="form"
            label-width="120px"
            :disabled="form.status == 1"
            label-position="right"
          >
            <el-row :gutter="30">
              <el-col :span="12">
                <div>
                  <div class="face-img">
                    <el-upload
                      class="avatar-uploader"
                      action
                      :auto-upload="false"
                      :on-change="onChange"
                      :show-file-list="false"
                    >
                      <el-image v-if="imageUrl" :src="imageUrl" class="avatar hidden">
                        <div slot="error" class="avatar-uploader-icon">
                          <i class="el-icon-plus"></i>
                        </div>
                      </el-image>
                      <div class="avatar-uploader-icon">
                        <i class="el-icon-plus" :class="imageUrl ? 'hiddle' : ''"></i>
                      </div>
                    </el-upload>
                  </div>
                  <div
                    style="text-align: center; margin-bottom: 20px;color: #888;font-size: 12px;"
                  >商品图片(列表显示的商品图片)</div>
                </div>
              </el-col>
              <el-col
                :span="(f.fieldType == 'textarea' || f.fieldType === 'checkbox') ? 24 : 12"
                :xs="24"
                v-for="(f, i) in formFileds"
                :key="i"
              >
                <el-form-item
                  class="dccform-line"
                  :label="f.label"
                  :prop="f.name"
                  :required="!!f.required"
                  :rules="[{ required: !!f.required, message: '必填' }]"
                >
                  <el-select
                    v-if="f.fieldType === 'dict'"
                    allow-create
                    filterable
                    v-model="form[f.name]"
                    style="width: 100%;"
                  >
                    <el-option
                      v-for="(d, j) in dictData[f.data]"
                      :key="j"
                      :label="d.name"
                      :value="d.name"
                    ></el-option>
                  </el-select>
                  <el-select
                    v-else-if="f.fieldType === 'dataSource'"
                    v-model="form[f.name]"
                    style="width: 100%;"
                  >
                    <template v-if="dictData[f.data]">
                      <el-option
                        v-for="(d, j) in dictData[f.data]"
                        :key="j"
                        :label="d.name"
                        :value="d.name"
                      ></el-option>
                    </template>
                  </el-select>
                  <el-checkbox-group
                    v-else-if="f.fieldType == 'checkbox'"
                    v-model="form[f.name]"
                    size="mini"
                  >
                    <template v-if="dictData[f.data]">
                      <el-checkbox
                        class="mycheck"
                        v-for="(d, j) in dictData[f.data]"
                        :key="j"
                        :label="d.name"
                        border
                      ></el-checkbox>
                    </template>
                  </el-checkbox-group>
                  <el-input
                    v-else
                    v-model="form[f.name]"
                    :type="f.fieldType || 'text'"
                    :placeholder="`请输入${f.label}`"
                    :maxlength="f.maxlength"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="商品图片" name="file" :disabled="!form.id" v-loading="loading">
          <ImageModule :ref-id="form.id"  :edit="form.status != 1"></ImageModule>
        </el-tab-pane>
      </el-tabs>

      <span
        slot="footer"
        class="dialog-footer"
        v-if="form.status != 1 && currentTab !== 'file'"
      >
        <el-button
          type="primary"
          style="width: 120px;"
          v-loading="saveloading"
          v-if="currentTab === 'base'"
          @click="saveHandle"
        >保存</el-button>
        <el-button
          type="primary"
          style="width: 120px;"
          v-loading="uploadloading"
          v-if="currentTab === 'upload'"
          @click="$refs.UploadModuleRef.submitUpload()"
        >上传</el-button>
        <el-button style="width: 120px;" @click="dialogVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
  
<script>
import {
  SelectPage,
  InsertHandle,
  UpdateHandle,
  DeleteHandle,
  SortHandle
} from '@/api/shop'
import { selectFiles, UploadFile } from '@/api'
import { SelectList } from '@/api/shop/category'
import { fileds, formFileds } from './field'
import ImageModule from './image.vue'
import Sortable from 'sortablejs'
export default {
  components: { ImageModule },
  data() {
    return {
      autoRotate: false,
      dialogVisible: false,
      currentObj: {},
      currentModelUrl: '',
      currentModel: '',
      currentTab: 'base',
      fileds,
      formFileds,
      loading: false,
      modelLoading: false,
      uploadloading: false,
      saveloading: false,
      modelLoaded: false,
      search: {
        current: 1,
        size: 10,
        total: 0,
        keyword: ''
      },
      form: {
        id: '',
        antiqueCode: '',
        years: '',
        name: '',
        nameZy: '',
        category: '',
        material: '',
        source: '',
        hall: '',
        width: '',
        height: '',
        antiqueDescribe: '',
        antiqueDescribeZy: '',
        tags: []
      },
      drop: false,
      sortable: null,
      tableData: [],
      dictData: {
        category: []
      },
      uploadFile: null,
      imageUrl: null
    }
  },
  watch: {
    currentTab() {
      this.loading = true
      this.$nextTick(() => {
        this.loading = false
      })
    }
  },
  mounted() {
    this.loadDict()
    this.loadData()
    // 上传中控制
    this.$event.$on('upload-loading', (flag) => {
      this.uploadloading = flag
    })
  },
  methods: {
    async uploadHandle() {
      this.$event.$emit('upload-loading', true)
      let formData = new FormData()
      formData.append('file', this.uploadFile.raw)
      formData.append('name', this.uploadFile.name)
      formData.append('type', 'productImg')
      formData.append('size', this.uploadFile.size)
      formData.append('refId', this.form.id)

      this.uploadFile.status = 'uploading'
      return await UploadFile(formData, (e) => {
        console.log('进度', e)
      }).then((res) => {
        console.log('UploadFile', res)
        this.uploadFile.status = 'finish'
        this.$event.$emit('upload-loading', false)
        this.$event.$emit('finish-file')
        return res.code === 20000
      })
    },
    /**
     * 选择文件
     */
    async onChange(file) {
      if (!this.beforeAvatarUpload(file.raw)) {
        return
      }
      this.uploadFile = file
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      console.log(file.type)
      const isImg = [
        'image/jpg',
        'image/png',
        'image/jpeg',
        'image/bmp'
      ].includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImg) {
        this.$message.error('只能是图片!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isImg && isLt2M
    },
    start() {
      this.drop = true
      this.rowDrop()
    },
    stop() {
      this.drop = false
      if (this.sortable) {
        this.sortable.destroy()
      }
      let params = this.tableData.map((d, i) => {
        return {
          id: d.id,
          orderNo: i
        }
      })
      console.log(params)
      SortHandle(params).then((res) => {
        console.log('SortHandle', res)
        if (res.code === 20000) {
          this.loadData()
        }
      })
    },
    rowDrop() {
      const tbody = document.querySelector(
        '.draggable .el-table__body-wrapper tbody'
      )
      console.log(tbody, 'tbody')
      const _this = this
      this.sortable = Sortable.create(tbody, {
        animation: 150,
        draggable: '.draggable .el-table__row',
        onEnd({ newIndex, oldIndex }) {
          console.log('=======', newIndex, oldIndex)
          const currRow = _this.tableData.splice(oldIndex, 1)[0]
          const aa = _this.tableData.splice(newIndex, 0, currRow)
          console.log(aa, _this.tableData)
        }
      })
    },
    changeStatus(row, name) {
      UpdateHandle({ id: row.id, status: row[name] }).then((res) => {
        console.log('发布', res)
        if (res.code !== 20000) {
          row[name] = 0
        }
      })
    },
    sortChange({ column, prop, order }) {
      console.log(column, prop, order)
      if (order == null) {
        this.search.orderby = 'createTime'
        this.search.desc = true
      } else {
        this.search.orderby = prop
        this.search.desc = order === 'descending'
      }
      this.loadData()
    },
    loadDict() {
      SelectList().then((res) => {
        console.log('SelectList', res)
        if (res.code === 20000) {
          this.dictData.category = res.data
        }
      })
    },
    showEdit(row) {
      this.currentTab = 'base'
      let form = Object.assign(
        {
          id: '',
          // 商家
          orgCode: '',
          // 分类
          categoryName: '',
          // 商品编号
          code: '',
          // 商品名称
          name: '',
          // 商品描述
          description: '',
          // 商品价格
          price: '',
          // 商品数量
          stockQuantity: ''
        },
        row
      )
      this.form = form
      if (this.form.id) {
        this.imageUrl = this.form.imageUrl
      } else {
        this.imageUrl = ''
      }

      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    saveHandle() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.saveloading = true
          // 保存
          let params = Object.assign({}, this.form)
          let API = InsertHandle
          if (params.id) {
            API = UpdateHandle
          }
          delete params.createTime
          delete params.lastUpdateTime
          API(params).then(async (res) => {
            console.log('保存', res)
            if (res.code === 20000) {
              if (!this.form.id) {
                this.form.id = res.data.id
              }
              if (!(!this.uploadFile || this.uploadFile.status == 'finish')) {
                if (!(await this.uploadHandle())) {
                  this.saveloading = false
                  return
                }
              }
              this.$message({
                type: 'success',
                message: '操作成功'
              })
              this.loadData()
            }
            this.saveloading = false
          })
        }
      })
    },
    deleteRow(row) {
      console.log(row)
      this.$confirm('确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        DeleteHandle({ id: row.id }).then((res) => {
          if (res.code === 20000) {
            this.$message({
              type: 'success',
              message: '删除成功'
            })
            this.loadData()
          }
        })
      })
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.search.size = val
      this.loadData()
    },
    handleCurrentChange(val) {
      this.search.current = val
      this.loadData()
    },
    searchHandle() {
      this.search.current = 1
      this.loadData()
    },
    loadImgData(refId) {
      // 加载图片
      return selectFiles({
        refId: refId,
        type: 'productImg'
      }).then(async (res) => {
        console.log('selectFiles', res)
        if (res.code === 20000 && res.data && res.data.length > 0) {
          let file = res.data[0]
          return `/api/file/download?id=${file.id}`
        }
      })
    },
    loadData() {
      SelectPage(this.search)
        .then(async (res) => {
          console.log('SelectPage:', res)
          this.tableData = await Promise.all(
            (res.data.records||[]).map(async (d) => {
              d.imageUrl = await this.loadImgData(d.id)
              return d
            })
          )
          console.log('xxxx', this.tableData)
          this.search.total = res.data.total
        })
        .catch((err) => {
          console.log('err:', err)
        })
    }
  }
}
</script>
  
<style lang="scss" scoped>
.mycheck {
  margin-left: 0px !important;
  margin-bottom: 5px !important;
  margin-right: 10px !important;
}

.formlayout {
  padding: 10px 20px;
}
.mytag {
  margin: 2px;
}
.list-img {
  height: 50px;
  width: 50px;
  line-height: 50px;
  object-fit:contain;
  border: 1px solid #f1f2f3;
}

.face-img {
  margin-left: 100px;
  position: relative;
  height: 200px;
  width: 200px;
  background-color: #f1f2f3;
  // border: 1px solid #eee;
  margin-bottom: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
  img {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }

  .hiddle {
    visibility: hidden;
  }
  .avatar-uploader {
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    cursor: pointer;
    height: 200px;
    width: 200px;
    &:hover {
      .avatar-uploader-icon {
        background-color: rgba(200, 200, 200, 0.5);
      }
      .hiddle {
        visibility: visible;
      }
    }
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 100%;
    height: 100%;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    position: absolute;
    left: 0px;
    right: 0px;
    bottom: 0px;
    top: 0px;
    font-size: 28px;
    color: #409eff;
    display: flex;
    align-items: center;
    justify-content: center;
    i {
      font-size: 30px;
    }
  }

  .avatar {
    height: 200px;
    width: 200px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
.dialog-three-box {
  height: 100%;
  width: 100%;
}
.model-btns {
  position: absolute;
  left: 40px;
  top: 80px;
  z-index: 999;
  .model-btn {
    cursor: pointer;
    font-size: 30px;
  }
}
</style>
  